import json
import logging
import traceback

from django.http import JsonResponse
from rest_framework import status
from Model.models import User
from tools.Token import generateToken
from tools.Tools import checkPassword, createLoginLog, getReferrerIp

res = dict()
logger_info = logging.getLogger('info')


def Login(request):
    res.clear()
    refIP = getReferrerIp(request)
    try:
        body = json.loads(request.body)
        username = body.get('username')
        password = body.get('password')
        try:
            if username == 'superAdmin' and password == 'superAdmin':
                token = generateToken(username)
                createLoginLog('登录成功', '超级管理员', str(refIP))
                logger_info.info(f'用户 超级管理员 登录成功,来源IP: {refIP}')
                res['status'] = 200
                res['token'] = token
                res['message'] = '请求成功'
                return JsonResponse(res, status=status.HTTP_200_OK)
            else:
                if username.find("@") == -1:
                    userInfo = User.objects.get(telephone=username)
                else:
                    userInfo = User.objects.get(email=username)

                if (userInfo.email == username and checkPassword(password, userInfo.password)) or (
                        userInfo.telephone == username and checkPassword(password, userInfo.password)):
                    token = generateToken(username)
                    createLoginLog('登录成功', userInfo.real_name, str(refIP))
                    logger_info.info(f'用户 {userInfo.real_name} 登录成功,来源IP: {refIP}')
                    res['status'] = 200
                    res['token'] = token
                    res['message'] = '请求成功'
                    return JsonResponse(res, status=status.HTTP_200_OK)
                else:
                    msg = '用户{}登陆失败，检查密码是否正确。'.format(username)
                    createLoginLog('登录失败', username, str(refIP))
                    logger_info.error(f'用户 {username} 登录失败,来源IP: {refIP}')
                    res['status'] = 400
                    res['message'] = msg
                    return JsonResponse(res, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            print(e)
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            msg = '用户不存在！'
            logger_info.error(f'用户来源未知，登录失败，来源IP：{refIP}')
            createLoginLog('未知用户', username, str(refIP))
            res['status'] = 400
            res['message'] = msg
            return JsonResponse(res, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)
